import { login, getInfo, logout, logouts } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import roter from "../../router/routers";
import { Message } from "element-ui";

const user = {
  state: {
    token: getToken(),
    user: {},
    roles: [],
    // 第一次加载菜单时用到
    loadMenus: false,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USER: (state, user) => {
      state.user = user;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_LOAD_MENUS: (state, loadMenus) => {
      state.loadMenus = loadMenus;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const rememberMe = userInfo.rememberMe;
      return new Promise((resolve, reject) => {
        let prarms = {
          login_name: userInfo.username, //登陆用户名
          password: userInfo.password, //密码
        };
        let user = {
          roles: ["admin"],
        };
        login(prarms)
          .then((res) => {
            Message({
              type: res.code == 0 ? "success" : "error",
              message: res.msg || "",
            });
            sessionStorage.setItem("userObj", JSON.stringify(res.result));
            setToken(res.result.token, rememberMe);
            commit("SET_TOKEN", res.result.token);

            setUserInfo(user, commit);
            // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js
            commit("SET_LOAD_MENUS", true);

            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            setUserInfo(res, commit);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 退出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        let prarms = {
          func: "loginOut",
          token: JSON.parse(sessionStorage.getItem("userObj")).token || "", //API接口访问令牌
        };
        logouts(prarms)
          .then((res) => {
            logOut(commit);
            sessionStorage.removeItem("userObj");
            resolve();
          })
          .catch((error) => {
            logOut(commit);
            reject(error);
          });
      });
    },

    updateLoadMenus({ commit }) {
      return new Promise((resolve, reject) => {
        commit("SET_LOAD_MENUS", false);
      });
    },
    YesupdateLoadMenus({ commit }) {
      return new Promise((resolve, reject) => {
        commit("SET_LOAD_MENUS", true);
      });
    },
  },
};

export const logOut = (commit) => {
  commit("SET_TOKEN", "");
  commit("SET_ROLES", []);
  removeToken();
};

export const setUserInfo = (res, commit) => {
  console.log("路由第一个参数", res, res.roles, "路由第2个参数", commit);
  // 如果没有任何权限，则赋予一个默认的权限，避免请求死循环
  if (res.roles.length === 0) {
    commit("SET_ROLES", ["ROLE_SYSTEM_DEFAULT"]);
  } else {
    commit("SET_ROLES", res.roles);
  }
  // commit("SET_USER", res.user);
};

export const YessetUserInfo = (res, commit) => {
  commit("SET_ROLES", ["admin"]);
};

export default user;
